import {
  createRouter,
  createWebHistory,
  type Router,
  type NavigationGuardNext,
  type RouteLocationNormalized,
  type RouteRecordRaw,
} from 'vue-router';
import { nextTick } from 'vue';

// Pinia Store
import GlobalStore from '@/store/GlobalStore';
import store from '@/store';

// Components
import Dashboard from '@/views/dashboard/Dashboard.vue';
import Team from '@/views/Team/Team.vue';
import IDO from '@/views/ido/index.vue';
import IDODetail from '@/views/ido/IDODetail.vue';
import HomePage from '@/views/home/index.vue';
import Profile from '@/views/profile/index.vue';
import NFT from '@/views/nft/index.vue';
import Course from '@/views/course/index.vue';
import WithdrawalFailed from '@/views/withdrawalFailed/index.vue';
import storage from '@/utils/storage';
// import storage from "@/utils/storage";

/** Router Rules */
const routes: RouteRecordRaw[] = [
  // {
  //   path: '/',
  //   redirect: `/${storage.getItem('lang')}`,
  // },
  {
    // path: `/${storage.getItem('lang')}`,
    path: '/',
    name: 'Home',
    component: HomePage,
  },
  {
    // path: `/dashboard/${storage.getItem('lang')}`,
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
  },
  {
    // path: `/dashboard/${storage.getItem('lang')}`,
    path: '/team',
    name: 'Team',
    component: Team,
  },
  {
    // path: `/ido/${storage.getItem('lang')}`,
    path: '/ido',
    name: 'IDO',
    component: IDO,
  },
  {
    // path: `/ido/detail/:id/${storage.getItem('lang')}`,
    path: '/ido/detail/:id',
    name: 'IDODetail',
    component: IDODetail,
  },
  {
    // path: `/profile/${storage.getItem('lang')}`,
    path: '/profile',
    name: 'Profile',
    component: Profile,
  },
  {
    path: '/nft',
    name: 'NFT',
    component: NFT,
  },
  {
    path: '/course',
    name: 'Course',
    component: Course,
  },
  {
    path: '/withdrawalFailed',
    name: 'WithdrawalFailed',
    component: WithdrawalFailed,
  },
];

/** Vue Router */
const router: Router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // createWebHashHistory(import.meta.env.BASE_URL)
  routes,
  scrollBehavior (to, from, savedPosition) {
    console.log(to, from, savedPosition);
    // // return desired position
    // if (savedPosition) {
    //   return savedPosition
    // } else {
    //   return { top: 0 }
    // }

    return { top: 0 };
  },
});

/** passing Pinia instance directly */
const globalStore = GlobalStore(store);

router.beforeEach(
  async (
    _to: RouteLocationNormalized,
    _from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    // Show Loading
    globalStore.setLoading(true);
    await nextTick();

    storage.setItem('tab', _to.name);

    next();
  }
);

router.afterEach(() => {
  // Hide Loading
  globalStore.setLoading(false);
});

export default router;
